package 回显服务器;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:客户端
 * User: lenovo
 * Date: 2022-10-17
 * Time: 22:08
 */
public class UDPEchoClient1 {
    DatagramSocket socket = null;
    //待会儿访问服务器时要用到
    String serveIp;
    int servePort;
    //构造方法
    public UDPEchoClient1(String serveIp, int servePort) throws SocketException {
        //由主机来分配空闲端口
        this.socket = new DatagramSocket();
        this.serveIp = serveIp;
        this.servePort = servePort;
    }
    public void start() throws IOException {
        while (true){
            //1.发送请求
            //从控制台输入内容
            System.out.println(">:");
            Scanner scanner = new Scanner(System.in);
            String requst = scanner.next();
            //构建数据报 指定服务器的ip和端口号
            DatagramPacket requstPacket = new DatagramPacket(requst.getBytes(),0,requst.getBytes().length,
                    InetAddress.getByName(serveIp),this.servePort);
            //发送请求
            socket.send(requstPacket);
            //2.接收服务器的响应
            DatagramPacket responsePacke = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacke);
            //将请求转化成字符串进行打印
            String response = new String(responsePacke.getData(),0,responsePacke.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPEchoClient1 client = new UDPEchoClient1("127.0.0.1",9090);
        client.start();
    }
}
